package org.devocean.groupbuying.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.devocean.groupbuying.dao.PromotionDAO;
import org.devocean.groupbuying.domain.Plan;
import org.devocean.groupbuying.domain.Promotion;
import org.devocean.groupbuying.domain.SerialKey;
import org.devocean.groupbuying.domain.Voucher;
import org.springframework.stereotype.Repository;

@Repository
public class PromotionDAOImpl implements PromotionDAO {

	@PersistenceContext
	private EntityManager em;
	

	public List<Promotion> findAllPromotions() {

		return em.createQuery("select p from Promotion p", Promotion.class)
				.getResultList();
	}

	public long countPromotion() {
		return em.createQuery("select count(p) from Promotion p", long.class)
				.getSingleResult();
	}

	public Promotion findPromotionById(Integer promotionID) {
		return em.find(Promotion.class, promotionID);
	}

	public void deletePromotion(Integer promotionID) {
		final Promotion promotion = em.find(Promotion.class, promotionID);
		if (promotion != null) {
			em.remove(promotion);
		}

	}

	public Promotion savePromotion(Promotion promotion) {
		em.persist(promotion);
		return promotion;
	}

	public Promotion updatePromotion(Promotion promotion) {
		Promotion merged = em.merge(promotion);
		return merged;
	}

	public List<Promotion> findPromotionsByProduct(Integer productID) {
		return (List<Promotion>) em.createQuery("select p from Promotion p " +
				"INNER JOIN  p.plan pl " +
				"INNER JOIN  pl.product pr " +
				"WHERE pr.productID=:pid", Promotion.class)
				.setParameter("pid", productID)
				.getResultList();
	}

	public List<Promotion> getPromotionsByPlan(Integer planID) {
		return em.createQuery("SELECT p FROM Promotion p INNER JOIN p.plan pl WHERE pl.planID=:planID", Promotion.class)
				.setParameter("planID", planID)
				.getResultList();
	}

}
